<template>
  <div class="grid-setting"
       id="grid-setting">
    <el-radio-group v-model="activeSetting"
                    size="mini">
      <el-radio-button label="gridSetting">{{$t('custom.component.gadget.gridOption')}}</el-radio-button>
      <el-radio-button label="columnsSetting">{{$t('custom.component.gadget.columnsSetting')}}</el-radio-button>
      <!--<el-radio-button label="event">Event</el-radio-button>-->
    </el-radio-group>
    <el-form ref="gridSetting"
             :model="setting"
             label-position="top"
             v-show="activeSetting==='gridSetting'"
             style="height:auto;">
      <!-- <div>11---{{setting.report.associatedFields}}</div> -->
      <el-form-item label="gridLines">
        <el-select v-model="setting.report.gridLines"
                   placeholder="Please select">
          <el-option v-for="(item,index) in gridLinesOptions"
                     :key="index"
                     :label="item"
                     :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Associated fields">
        <div v-if="indexs<2" v-for="(its,indexs) in setting.report.associatedFields"
             :key="indexs"
             style="margin-bottom:10px">
          <el-select v-model="its.value"
                     placeholder="Please select"
                     @change="associatedChange(indexs)"
                     filterable
                     :disabled="its.value === 'default'">
            <el-option v-for="(item,index) in setting.report.columns"
                       :key="index"
                       :label="item.field"
                       :value="item.field"></el-option>
          </el-select>
          <el-tooltip :open-delay="1000"
                      class="item"
                      effect="dark"
                      content="Add new field"
                      placement="top">
            <el-button style="font-size: 16px;margin-left: 20px"
                       type="text"
                       size="mini"
                       :disabled="disabledAdd"
                       icon="el-icon-circle-plus-outline"
                       @click="addRow()"></el-button>
          </el-tooltip>
          <el-tooltip :open-delay="1000"
                      class="item"
                      effect="dark"
                      content="Delete"
                      placement="top">
            <el-button style="margin-left: 20px;font-size: 16px;"
                       type="text"
                       size="mini"
                       :disabled="indexs===0"
                       icon="el-icon-delete"
                       @click="deleteSelectedRow(indexs)"></el-button>
          </el-tooltip>
        </div>
      </el-form-item>
      <el-form-item label="Toolbar">
        <el-checkbox-group v-model="setting.report.toolbar">
          <el-checkbox label="PdfExport"></el-checkbox>
          <!-- <el-checkbox label="ExcelExport"></el-checkbox> -->
          <el-checkbox label="CsvExport"></el-checkbox>
          <el-checkbox label="ColumnChooser"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!--<el-form-item label="showColumnChooser">
        <el-switch v-model="setting.report.showColumnChooser"></el-switch>
      </el-form-item>-->
      <el-form-item label="Show Paging">
        <el-switch v-model="setting.report.allowPaging"></el-switch>
      </el-form-item>
      <el-form-item label="Show Export Option">
        <el-switch v-model="setting.report.showExportOption"></el-switch>
      </el-form-item>
    </el-form>
    <div v-show="activeSetting==='columnsSetting'">
      <el-tabs type="card"
               style="margin-top:20px"
               size="mini"
               v-model="activeName"
               @tab-click="handleClick">
        <el-tab-pane :label="its.value"
                     :name="its.value"
                     v-for="(its,indexs) in setting.report.associatedFields"
                     :key="indexs">
          <div>
            <el-switch v-model="its.expandAllColumn"
                       active-text="Expand All"
                       inactive-text=""
                       @change="expandAll(its.expandAllColumn,indexs)"></el-switch>
            <draggable handle=".mover"
                       filter=".edititem"
                       v-model="its.fields"
                       chosenClass="chosen"
                       forceFallback="true"
                       animation="1000">
              <transition-group>
                <div class="item_drag"
                     v-for="(item,index) in its.fields"
                     :key="item.field">
                  <el-card class="column-card">
                    <el-row type="flex"
                            class="row-bg mover">
                      <el-col :span="16">
                        <div>
                          <span class="column-field">{{item.field}} </span><i class="column-type">: {{item.type}}</i>
                        </div>
                      </el-col>
                      <el-col :span="8">
                        <div style="float:right">
                          <el-tooltip :open-delay="1000"
                                      class="item"
                                      effect="dark"
                                      :content="item.visible ? 'Display Column ' : 'Hide Column'"
                                      placement="bottom-end">
                            <el-link style="float: left; border: none;"
                                     :underline="false"
                                     @click.native="toggleVisible(indexs,index, item.visible)"><i v-bind:class="[item.visible ? 'cuifont icon_eye_show': 'cuifont icon_eye_hide']"
                                 style="margin-left: 5px;"></i></el-link>
                          </el-tooltip>
                          <el-link style="margin-left:5px"
                                   class="column-link edititem"
                                   :underline="false"
                                   @click.native="showSettingClick(indexs,index, item.showSetting)"><i v-bind:class="[item.showSetting ? 'el-icon-arrow-up': 'el-icon-arrow-down','edititem']"
                               style="margin-left: 5px;"></i></el-link>
                          <!-- <el-link class="column-link" :underline="false" @click.native="upSortClick(indexs,index)" v-show="index != 0"><i class="el-icon-top"></i></el-link>
                                <el-link class="column-link" :underline="false" @click.native="downSortClick(indexs,index)" v-show="index != its.fields.length-1"><i class="el-icon-bottom"></i></el-link> -->
                        </div>
                      </el-col>
                    </el-row>
                    <el-form label-position="left"
                             v-show="item.showSetting"
                             label-width="120px"
                             style="border-top: 1px solid #EBEEF5;padding-top: 10px;">
                      <input hidden
                             name="field"
                             v-model="item.field" />
                      <el-form-item label="Header Text">
                        <el-input v-model="item.headerText"
                                  @input="forceUpdate"></el-input>
                      </el-form-item>
                      <el-form-item label="Text Align">
                        <el-select v-model="item.textAlign"
                                   @change="forceUpdate"
                                   placeholder="Please select">
                          <el-option label="Left"
                                     value="Left"></el-option>
                          <el-option label="Center"
                                     value="Center"></el-option>
                          <el-option label="Right"
                                     value="Right"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="Allow Filtering">
                        <el-switch v-model="item.allowFiltering"
                                   @change="forceUpdate"></el-switch>
                      </el-form-item>
                      <el-form-item label="Disable Html">
                        <el-switch v-model="item.disableHtmlEncode"
                                   @change="forceUpdate"></el-switch>
                      </el-form-item>
                      <!-- <el-form-item label="Aggregates" v-if="item.type === 'number'">
                                <el-checkbox-group v-model="item.aggregates" @change="checkboxChange($event,item)">
                                    <el-select multiple v-model="item.aggregates" placeholder="Please select" @change="selectChange($event,item)">
                                      <el-option :label="list.label" :value="list.value" v-for="list in aggregates" :key="list.label">
                                        <el-checkbox @click.native="(e) => {e.preventDefault()}" :label="list.label"></el-checkbox>
                                      </el-option>
                                    </el-select>
                                </el-checkbox-group>
                              </el-form-item> -->
                      <el-form-item label="Number Format"
                                    v-if="item.type==='number'&&AveragePoint(item.aggregates)">
                        <el-select v-model="item.decimalPoint"
                                   placeholder="Please select">
                          <el-option label="0"
                                     :value="0"></el-option>
                          <el-option label="0.0"
                                     :value="1"></el-option>
                          <el-option label="0.00"
                                     :value="2"></el-option>
                          <el-option label="0.000"
                                     :value="3"></el-option>
                          <el-option label="0.0000"
                                     :value="4"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-form>
                  </el-card>
                </div>
              </transition-group>
            </draggable>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>

<script>
import draggable from 'vuedraggable'
import Index from '../../dashboard-filter/index.vue'
export default {
  name: 'HierarchygridSetting',
  components: { Index, draggable },
  data () {
    return {
      activeName: 'default',
      dataSource: [],
      dataSourceColumns: [],
      activeSetting: 'gridSetting',
      gridLinesOptions: ['Default', 'Both', 'None', 'Horizontal', 'Vertical'],
      columnTemplates: ['linkFormat', 'boolFormat', 'progessFormat', 'dateFormat', 'progessFullFormat', 'ticketLinkFormat', 'timeEntryLinkFormat', 'textFormat'],
      expandAllColumn: false,
      setting: {
        headerTitle: '',
        headerDescription: '',
        drillThroughStatus: true,
        report: {
          gridLines: 'Default',
          associatedFields: [{ label: '', value: 'default', fields: [] }],
          showColumnMenu: true,
          allowResizing: true,
          allowFiltering: true,
          filterSettings: { type: 'Excel' },
          allowGrouping: true,
          showExportOption: false,
          allowPaging: true,
          allowExcelExport: true,
          allowPdfExport: true,
          toolbar: ['PdfExport', 'CsvExport', 'ColumnChooser'], // 'ExcelExport',
          showColumnChooser: true,
          groupOptions: { columns: ['name'] },
          allowReordering: true,
          allowSorting: true,
          allowTextWrap: true,
          pageSettings: { pageSize: 100, pageSizes: [10, 50, 100, 200, 1000], pageCount: 4 },
          groupSettings: {
            allowReordering: false,
            columns: [],
            disablePageWiseAggregates: false,
            enableLazyLoading: false,
            showDropArea: true,
            showGroupedColumn: false,
            showToggleButton: false
          },
          columns: [

          ]
        }

      },
      aggregates: [
        {
          label: 'Sum',
          value: 'Sum'
        },
        {
          label: 'Average',
          value: 'Average'
        },
        {
          label: 'Min',
          value: 'Min'
        },
        {
          label: 'Max',
          value: 'Max'
        },
        {
          label: 'Count',
          value: 'Count'
        }
      ]
    }
  },
  props: [
    'data'
  ],
  watch: {
    data (value, oldValue) {
      return this.updateSetting(value)
    },
    'setting.report.associatedFields': {
      handler: function (val) {
        var res = val.some(item => item.value === this.activeName)
        if (!res) this.activeName = 'default'
      },
      deep: true
    },
    
  },
  computed:{
    disabledAdd () {
      if(this.setting.report.associatedFields.length >1){
        return true
      }else{
        return false
      }
    }
  },
  created () {
    if (this.data) {
      this.$set(this.data)
    }
  },
  methods: {
    forceUpdate () {
      this.$forceUpdate()
    },
    associatedChange (indexs) {
      this.setting.report.associatedFields[indexs].fields = JSON.parse(JSON.stringify(this.setting.report.columns))
      this.setting.report.associatedFields[indexs].fields.forEach(item => {
        item.visible = true
        item.allowFiltering = true
        item.allowSorting = true
        item.disableHtmlEncode = false
        item.headerText = item.field
        item.textAlign = 'Left'
      })
      this.$forceUpdate()
      var res = this.setting.report.associatedFields.some(item => item.value === this.activeName)
      if (!res) this.activeName = 'default'
    },
    handleClick (tab, event) {
    },
    deleteSelectedRow (indexs) {
      if (this.setting.report.associatedFields.length === 1) {
        this.setting.report.associatedFields = [{ label: '', value: 'default', fields: [] }]
      } else {
        this.setting.report.associatedFields.splice(indexs, 1)
      }
    },
    addRow () {
      if(this.setting.report.associatedFields.length === 1){
      this.setting.report.associatedFields.push({ label: '', value: '', fields: [] })
      }
    },
    AveragePoint (aggregates) {
      if (aggregates && aggregates.includes('Average')) return true
      else return false
    },
    checkboxChange (e, item) {
      item.aggregates = e
      // this.$set(item, 'aggregates', e)
      this.$forceUpdate()
    },
    selectChange (e, item) {
      item.aggregates = e
      // this.$set(item, 'aggregates', e)
      this.$forceUpdate()
    },
    getData () {
      return this.setting
    },
    setColumns (dataSourceColumns) {
      dataSourceColumns.forEach(element => {
        if (element.type === 'number' && !element.hasOwnProperty('aggregates')) {
          element.aggregates = []
        }
        if (element.type === 'number' && !element.hasOwnProperty('decimalPoint')) {
          this.$set(element, 'decimalPoint', 2)
        }
      })
      this.setting.report.columns = dataSourceColumns
    },
    toggleVisible (indexs, index, visible) {
      // this.setting.report.columns[index].visible = !visible
      this.$set(this.setting.report.associatedFields[indexs].fields[index], 'visible', !visible)
      this.$forceUpdate()
    },
    showSettingClick (indexs, index, showSetting) {
      this.$set(this.setting.report.associatedFields[indexs].fields[index], 'showSetting', !showSetting)
      var res = this.setting.report.associatedFields[indexs].fields.every(item => item.showSetting)
      var result = this.setting.report.associatedFields[indexs].fields.some(item => !item.showSetting)
      if (res) {
        this.setting.report.associatedFields[indexs].expandAllColumn = true
      } else if (result) {
        this.setting.report.associatedFields[indexs].expandAllColumn = false
      }
      this.$forceUpdate()
    },
    expandAll (val, indexs) {
      this.setting.report.associatedFields[indexs].fields.forEach(item => {
        item.showSetting = val
      })
      this.$forceUpdate()
    },
    updateSetting (value, list, layerStatus) {
      let dataSourceColumns = []
      this.setting.report.toolbar = value.gadgetSetting.report.toolbar
      this.setting.report.associatedFields = value.gadgetSetting.report.associatedFields || [{ label: '', value: 'default', fields: [] }]
      this._.merge(this.setting, value.gadgetSetting)
      // this.setting={...this.setting,...value.gadgetSetting}
      // value set back
      if (value && value.gadgetSetting && value.gadgetSetting.report &&
        value.gadgetSetting.report.columns && value.gadgetSetting.report.columns.length > 0 && !layerStatus) {
        if (value.gadgetSetting.report.associatedFields[0].fields.length === 0) {
          value.gadgetSetting.report.associatedFields[0].fields = value.gadgetSetting.report.columns
        }
        this._.merge(this.setting, value.gadgetSetting)
        this.setting.report.toolbar = value.gadgetSetting.report.toolbar
        dataSourceColumns = value.gadgetSetting.report.columns
      } else if (value && list && list.length > 0) {
        list.forEach(item => {
          const itemObj = {
            field: item.name,
            headerText: item.name,
            textAlign: item.dbType === 'number' ? 'Right' : 'Left',
            allowEditing: true,
            allowFiltering: true,
            allowGrouping: true,
            allowReordering: true,
            allowSearching: true,
            allowSorting: true,
            autoFit: true,
            disableHtmlEncode: false,
            enableGroupByFormat: false,
            foreignKeyField: item.name,
            showColumnMenu: true,
            showInColumnChooser: true,
            sortDirection: 'Descending',
            type: this.convertType(item.dbType),
            template: null,
            visible: true,
            showSetting: false
          }
          if (value.gadgetSetting && value.gadgetSetting.report && value.gadgetSetting.report.columns) {
            const obj = this._.find(value.gadgetSetting.report.columns, { field: item.name })
            if (obj) {
              dataSourceColumns.push(obj)
            } else {
              dataSourceColumns.push(itemObj)
            }
          } else {
            dataSourceColumns.push(itemObj)
          }
        })
        for (let index = 0; index < this.setting.report.associatedFields.length; index++) {
          this.setting.report.associatedFields[index].fields = []
          this.setting.report.associatedFields[index].fields = JSON.parse(JSON.stringify(dataSourceColumns))
        }
      }
      this.setColumns(dataSourceColumns)
      this.$emit('update:data', this.setting)
      return dataSourceColumns
    },
    convertType (type) {
      return type
    },
    upSortClick (indexs, index) {
      // this.setting.report.associatedFields[indexs].fields[index]
      let temp = this.setting.report.associatedFields[indexs].fields[index - 1]
      this.$set(this.setting.report.associatedFields[indexs].fields, index - 1, this.setting.report.associatedFields[indexs].fields[index])
      this.$set(this.setting.report.associatedFields[indexs].fields, index, temp)
      this.$forceUpdate()
    },
    downSortClick (indexs, index) {
      let temp = this.setting.report.associatedFields[indexs].fields[index + 1]
      this.$set(this.setting.report.associatedFields[indexs].fields, index + 1, this.setting.report.associatedFields[indexs].fields[index])
      this.$set(this.setting.report.associatedFields[indexs].fields, index, temp)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss">
.grid-setting {
  .column-card {
    margin-top: 8px;
  }
  .el-card__body {
    padding: 5px 20px !important;
  }
  .column-field {
    font-weight: bold;
  }
  .column-type {
    color: #9ea1a7;
  }
  .column-link {
    float: left;
    border: none;
    margin-left: 3px;
  }
  .el-form-item .el-form-item {
    margin-bottom: 4px;
  }
}
</style>
<style scoped lang="scss">
.chosen {
  // border: solid 2px #3089dc !important;
}
.mover {
  // padding: 6px;
  // background-color: #fdfdfd;
  // border: solid 1px #eee;
  // margin-bottom: 10px;
  cursor: move;
  // width: 343px;
}
#grid-setting ::v-deep .el-switch__label.is-active {
  background-color: #fff !important;
}
</style>
